import Vue from "vue";
import Vuex from "vuex";
import { Toast } from "vant";
import axios from "axios";

Vue.use(Vuex);

export default new Vuex.Store({
  // 刷新页面，vuex 数据是会被清空的
  state: {
    token: localStorage.getItem("token") || "",
  },
  mutations: {
    set_token(state, payload = "") {
      state.token = payload;
    },
  },
  actions: {
    async login({ commit }, payload) {
      const { data } = await axios.post("/base/login", {
        username: payload.username,
        password: payload.password,
      });

      if (data.code !== 0) {
        // 抛出异常
        // 抛出的内容在外层的 catch 里面接收
        return Promise.reject(new Error(data.msg));
      }

      Toast("登录成功");

      // 1. 将 token 给存储起来
      localStorage.setItem("token", data.data.token);
      // 2. 还存一份到 vuex 中
      commit("set_token", data.data.token);
    },
  },
});
